package com.cloudspace.jindun.activity;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.view.Gravity;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import com.cloudspace.jindun.R;
import com.cloudspace.jindun.model.UserInfoResult;
import com.cloudspace.jindun.network.url.YXHttpUrl;
import com.cloudspace.jindun.user.UserSessionManager;
import com.cloudspace.jindun.utils.BitmapUtil;
import com.cloudspace.jindun.utils.FileUtil;
import com.cloudspace.jindun.utils.ObjUtil;
import com.cloudspace.jindun.utils.ToastMaker;
import com.cloudspace.jindun.window.SelectPicPopupWindow;
import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.File;
import java.io.FileNotFoundException;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;


//忘记密码
public class ForgetpassActivity extends CustomTitleBaseActivity {
    private static final String TAG = ForgetpassActivity.class.getSimpleName();

    @Bind(R.id.back)
    ImageView mBack;
    @Bind(R.id.register_et_id)
    EditText mRegisterEtId;
    @Bind(R.id.forget_iv_addImage)
    ImageView mForgetIvAddImage;
    @Bind(R.id.forget_bt_present)
    Button mForgetBtPresent;
    private String filename = "hz.png";

    private SelectPicPopupWindow menuWindow;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_forgetpass, false);
        ButterKnife.bind(this);
    }

    private File file;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            Bitmap bitmap = null;
            try {
                if (requestCode == 1) {
                    Uri selectedImage = data.getData();
                    bitmap = BitmapFactory.decodeStream(this
                            .getContentResolver().openInputStream(Uri.parse(selectedImage.toString())));
                } else if (requestCode == 2) {
                    if (data.getExtras() != null) {
                        Bundle bundle = data.getExtras();
                        bitmap = (Bitmap) bundle.get("data");//
                    }
                }

                saveImage(bitmap);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else {
            ToastMaker.showToastShort(R.string.not_choose_picture);
        }
    }

    private final String FILE_SAVE_NAME = "wjmm.png";

    @Nullable
    private void saveImage(Bitmap bitmap) throws FileNotFoundException {
        if (ObjUtil.isEmpty(bitmap)){
            ToastMaker.showToastShort(R.string.select_photo_error);
        }

        String filePath = FileUtil.getLocalFileImagePath() + FILE_SAVE_NAME;
        if ((filePath = BitmapUtil.compressImage(this, bitmap, filePath, 20)) == null) {
            ToastMaker.showToastShort(R.string.select_photo_error);
        }

        file = new File(filePath);
        mForgetIvAddImage.setImageBitmap(bitmap);
    }

    @OnClick({R.id.back, R.id.forget_iv_addImage, R.id.forget_bt_present})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.forget_iv_addImage:
                if (getCurrentFocus() != null) {
                    ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
                            .hideSoftInputFromWindow(getCurrentFocus()
                                            .getWindowToken(),
                                    InputMethodManager.HIDE_NOT_ALWAYS);
                }
                menuWindow = new SelectPicPopupWindow(ForgetpassActivity.this, itemsOnClick);
                //显示窗口
                menuWindow.showAtLocation(ForgetpassActivity.this.findViewById(R.id.forgment), Gravity.CENTER_HORIZONTAL, 0, 0); //设置layout在PopupWindow中显示的位置
                break;
            case R.id.forget_bt_present:
                String userId = mRegisterEtId.getText().toString();
                if (file != null) {
                    requestData(YXHttpUrl.LOGIN_WPASSWORD_URI, userId, filename, file);
                }

                break;
        }
    }

    private void requestData(String url, String userId, String filename, File file) {
        OkHttpUtils.post()
                .addFile("files", filename, file)
                .url(url)
                .addParams("userId", userId)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        ToastMaker.showToastShort(R.string.generic_error);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        if (response != null) {
                            Gson gson = new Gson();
                            UserInfoResult result = gson.fromJson(response, UserInfoResult.class);
                            if (result != null && result.status == 200) {
                                UserSessionManager.updateUserInfo(result.data);
                                RegisterActivity.showActivity(ForgetpassActivity.this);
                            } else {
                                ToastMaker.showToastShort(R.string.change_not_success);
                            }
                        }

                    }
                });
    }

    private View.OnClickListener itemsOnClick = new View.OnClickListener() {

        public void onClick(View v) {
            menuWindow.dismiss();
            switch (v.getId()) {
                case R.id.btn_take_photo:
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        requestPermissions(new String[]{Manifest.permission.CAMERA}, 2);
                        Intent intent2 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        startActivityForResult(intent2, 2);
                    } else {
                        Intent intent2 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        startActivityForResult(intent2, 2);
                    }
                    break;
                case R.id.btn_pick_photo:
                    Intent intent = new Intent();
                    //intent = new Intent(Intent.ACTION_GET_CONTENT);
                /* 开启Pictures画面Type设定为image */
                    intent.setType("image/*");
                /* 使用Intent.ACTION_GET_CONTENT这个Action */
                    intent.setAction(Intent.ACTION_GET_CONTENT);
                /* 取得相片后返回本画面 */
                    startActivityForResult(intent, 1);
                    break;
                default:
                    break;
            }
        }

    };

}
